package com.company.cloud.company.modules.mgr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.company.modules.base.entity.CashConfigInfo;
import com.company.cloud.company.modules.base.service.CashConfigInfoService;
import com.company.cloud.company.modules.cache.utils.CompanyConvertUtils;
import com.company.cloud.company.modules.mgr.controller.req.CashConfigQueryPageParam;
import com.company.cloud.company.modules.mgr.controller.req.CashConfigSaveParam;
import com.company.cloud.company.modules.api.response.CashConfigResp;
import com.company.cloud.company.modules.mgr.service.CashConfigMgrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CashConfigMgrServiceImpl implements CashConfigMgrService {

    @Autowired
    private CashConfigInfoService cashConfigInfoService;

    @Override
    public IPage<CashConfigResp> query(CashConfigQueryPageParam params, String companyNo) {
        IPage<CashConfigInfo> page = cashConfigInfoService.page(new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<CashConfigInfo>()
                        .eq(CheckUtils.hasText(companyNo), "company_no", companyNo)
                        .eq(CheckUtils.hasBigDecimal(params.getMiniCashFund()), "mini_cash_fund", params.getMiniCashFund())
                        .eq(CheckUtils.hasBigDecimal(params.getTaxCash()), "tax_cash", params.getTaxCash())
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
        );
        return page.convert(CompanyConvertUtils::getCashConfigResp);
    }

    @Override
    public void saveOrEdit(CashConfigSaveParam params, String companyNo, LoginSimpleUserInfo userInfo) {
        CashConfigInfo entity = CompanyConvertUtils.getCashConfigInfo(params, userInfo.getCompanyNo());
        CashConfigInfo old = cashConfigInfoService.getById(userInfo.getCompanyNo());
        if (old == null) {
            entity.addCreateParam(userInfo);
            entity.addEditParam(userInfo);
            cashConfigInfoService.save(entity);
        } else {
            entity.addEditParam(userInfo);
            cashConfigInfoService.updateById(entity);
        }
    }

    @Override
    public CashConfigResp get(String companyNo) {
        CashConfigInfo entity = cashConfigInfoService.getById(companyNo);
        return CompanyConvertUtils.getCashConfigResp(entity);
    }
}
